package com.project.common;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 七牛 文件上传   //todo 上传头像之后 删除之前的头像存储
 */
public class QiniuFileUploadUtil {

    public static String uploadHeadImg(File file) throws IOException {
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(Const.QINIU_ACCESS_KEY,Const.QINIU_SECRET_KEY);
        String upToken = auth.uploadToken(Const.QINIU_HEAD_IMG_BUCKET_NAME);
        Response response = uploadManager.put(file,null,upToken);
        //解析上传结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
        return putRet.key;
    }
}
